package com.mine.xpermission;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.activity.result.ActivityResultLauncher;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.mine.bean.PermissionBean;

import java.util.List;

public class PermissionManager {

    private static PermissionManager instance;
    private Activity activity;
    public static final int PERMISSION_REQUEST_CODE = 101;
    public static final int PERMISSION_REQUEST_FILE_MANAGER = 102;
    public static final int PERMISSION_ACTION_MANAGE_WRITE_SETTINGS = 103;
    public static final int PERMISSION_ACTION_MANAGE_UNKNOWN_APP_SOURCES = 104;
    //悬浮窗权限
    public static final int PERMISSION_ACTION_MANAGE_OVERLAY_PERMISSION = 105;

    PermissionCheckListener listener;
    private boolean isBroadRoot = false;

    public static PermissionManager getInstance(Activity activity) {
        if (instance == null) {
            synchronized (PermissionManager.class) {
                if (instance == null) {
                    instance = new PermissionManager(activity);
                }
            }
        }
        return instance;
    }

    public PermissionManager(Activity activity) {
        this.activity = activity;
    }

    /***
     * 检测权限是否全部通过
     */
    public boolean checkAllPermissionComplete(List<PermissionBean> permissionBeanList) {
        if (permissionBeanList == null || permissionBeanList.isEmpty()) {
            return true;
        }
        boolean isComplete = true;
        for (PermissionBean permissionBean : permissionBeanList) {
            String action = permissionBean.getPermissionAction();
            boolean isOver = checkAppPermission(action);
            if (!isOver) {
                isComplete = false;
                break;
            }
        }
        return isComplete;
    }

    /***
     * 检查权限是否通过
     *  public static final int PERMISSION_GRANTED = 0;  同意
     *  public static final int PERMISSION_DENIED = -1;  拒接
     */
    public boolean checkAppPermission(String permissionName) {
        if (TextUtils.isEmpty(permissionName)) {
            return true;
        }
        if (permissionName.equals(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)) {
            return checkFileManagerPermission();
        }
        if (permissionName.equals(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)) {
            return checkActionManageUnknowAppSource();
        }
        if (permissionName.equals(Settings.ACTION_MANAGE_WRITE_SETTINGS)) {
            return checkAppWriteSystemPermission();
        }
        if (permissionName.equals(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)) {
            return checkAppOverLayPermission();
        }
        int checkStatu = ContextCompat.checkSelfPermission(activity, permissionName);
        if (checkStatu != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

    /***
     * 检查指定应用是否被允许安装未知来源应用
     * @return
     */
    private boolean checkActionManageUnknowAppSource() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PackageManager pm = activity.getPackageManager();
            return pm.canRequestPackageInstalls();
        }
        int appStatues = android.provider.Settings.Secure.getInt(activity.getContentResolver(), android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
        return appStatues == 1;
    }

    public void setRequestPermissionListener(PermissionCheckListener permissionCheckListener) {
        this.listener = permissionCheckListener;
    }

    /***
     * 执行方法
     */
    public void requestPermissionSingle(String needRequest) {
        if (needRequest.equals(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)) {
            //未知APK来源权限
            boolean isSuccess = checkActionManageUnknowAppSource();
            if (isSuccess) {
                listener.checkPermissionComplete(needRequest);
                return;
            }
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            // 指定要授权的应用包名
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivityForResult(intent, PERMISSION_ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            if (isBroadRoot && listener != null) {
                listener.checkPermissionComplete(needRequest);
            }
            return;
        }
        if (needRequest.equals(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)) {
            //文件管理权限
            boolean isSuccess = checkFileManagerPermission();
            if (isSuccess) {
                listener.checkPermissionComplete(needRequest);
                return;
            }
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivityForResult(intent, PERMISSION_REQUEST_FILE_MANAGER);
            if (isBroadRoot && listener != null) {
                listener.checkPermissionComplete(needRequest);
            }
            return;
        }
        if (needRequest.equals(Settings.ACTION_MANAGE_WRITE_SETTINGS)) {
            //系统设置权限
            boolean isSuccess = checkAppWriteSystemPermission();
            if (isSuccess) {
                listener.checkPermissionComplete(needRequest);
                return;
            }
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivityForResult(intent, PERMISSION_ACTION_MANAGE_WRITE_SETTINGS);
            if (isBroadRoot && listener != null) {
                listener.checkPermissionComplete(needRequest);
            }
            return;
        }

        if (needRequest.equals(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)) {
            //悬浮窗权限
            boolean isSuccess = checkAppOverLayPermission();
            if (isSuccess) {
                listener.checkPermissionComplete(needRequest);
                return;
            }
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivityForResult(intent, PERMISSION_ACTION_MANAGE_OVERLAY_PERMISSION);
            if (isBroadRoot && listener != null) {
                listener.checkPermissionComplete(needRequest);
            }
            return;
        }
        //常规权限: 可能被客户拒绝2次，如果不在询问的话，直接交给前台界面处理
        boolean currentStatue = ActivityCompat.shouldShowRequestPermissionRationale(activity, needRequest);
        logPermission("currentStatue=" + currentStatue);
        if (currentStatue) {
            if (listener != null) {
                listener.showGotoAppDetailDialog(needRequest);
            }
            return;
        }
        String[] request = new String[]{needRequest};
        ActivityCompat.requestPermissions(activity, request, PERMISSION_REQUEST_CODE);
        if (isBroadRoot && listener != null) {
            listener.checkPermissionComplete(needRequest);
        }
    }

    private boolean checkAppOverLayPermission() {
        return Settings.canDrawOverlays(activity);
    }

    private void logPermission(String s) {
        Log.d("permissionLog", s);
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        String permissionName = permissions[0];
        int status = grantResults[0];
        if (status != PackageManager.PERMISSION_GRANTED) {
            if (listener != null) {
                listener.showGotoAppDetailDialog(permissionName);
            }
            return;
        }
        listener.checkPermissionComplete(permissionName);
    }

    /***
     * 特殊权限操作监听
     */
    public void onRequestPermissionsActivityResult(int code) {
        if (listener == null) {
            return;
        }

        if (code == PERMISSION_ACTION_MANAGE_OVERLAY_PERMISSION) {
            //悬浮窗权限
            boolean isOverLay = checkAppOverLayPermission();
            if (isOverLay) {
                listener.checkPermissionComplete(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                return;
            }
            listener.showGotoAppDetailDialog(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            return;
        }

        if (code == PERMISSION_ACTION_MANAGE_UNKNOWN_APP_SOURCES) {
            //未知APK来源授权
            boolean isApkSource = checkActionManageUnknowAppSource();
            if (isApkSource) {
                listener.checkPermissionComplete(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                return;
            }
            listener.showGotoAppDetailDialog(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            return;
        }
        if (code == PERMISSION_REQUEST_FILE_MANAGER) {
            //文件管理权限
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
                listener.checkPermissionComplete(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                return;
            }
            if (Environment.isExternalStorageManager()) {
                listener.checkPermissionComplete(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                return;
            }
            listener.showGotoAppDetailDialog(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            return;
        }
        if (code == PERMISSION_ACTION_MANAGE_WRITE_SETTINGS) {
            //系统写入权限
            if (Settings.System.canWrite(activity)) {
                listener.checkPermissionComplete(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                return;
            }
            listener.showGotoAppDetailDialog(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        }
    }

    /***
     * 是否有系统Write修改权限
     * @return
     */
    private boolean checkAppWriteSystemPermission() {
        if (Settings.System.canWrite(activity)) {
            return true;
        }
        return false;
    }


    /***
     * 检查高级文件管理权限
     * @return
     */
    private boolean checkFileManagerPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            return true;
        }
        if (Environment.isExternalStorageManager()) {
            return true;
        }
        return false;
    }


    public void setBroadRoot(boolean isBroadRoot) {
        this.isBroadRoot = isBroadRoot;
    }
}
